package com.labofjet.system.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

public class FreeMarkerUtil {

    private static Logger log = LoggerFactory.getLogger(FreeMarkerUtil.class);

    public static Configuration configuration;

    static {
        configuration = new Configuration(Configuration.VERSION_2_3_23);
        configuration.setObjectWrapper(Configuration.getDefaultObjectWrapper(Configuration.VERSION_2_3_23));
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(FreeMarkerUtil.class, "/");
    }

    /**
     * 获取解析后的值.
     *
     * @param temp
     * @return
     */
    public static String getProcessValue(Map<String, Object> param, String temp) {
        try {
            Template template = new Template("",
                    new StringReader("<#escape x as (x)!>" + temp + "</#escape>"),
                    configuration);
            StringWriter sw = new StringWriter();
            template.process(param, sw);
            return sw.toString();
        } catch (Exception e) {
            log.error("freemarker解析失败", e);
            throw new RuntimeException(e);
        }
    }
}
